import { defineStore } from 'pinia'
import { computed, onMounted, reactive, ref } from 'vue'

import { MessagePlugin } from 'tdesign-vue-next'
import { apiUrl, get, post } from '@/utils/api'
import { useOrderNo } from '@/utils/orderNo'

export const useBuyStore = defineStore('buy', () => {
  const shopInfo = ref([
    {
      id: '',
      price: '',
      name: '',
      description: '',
      imageUrl: ''
    }
  ])
  const orderInfo = reactive({
    uid: '',
    pid: '',
    title: '',
    amount: '',
    orderTradeNo: '',
    type: 0
  })
  const payTypeVisible = ref(false)

  const buyAuthorization = (item: any) => {
    payTypeVisible.value = true
    orderInfo.title = item.name
    orderInfo.amount = item.price
    orderInfo.orderTradeNo = useOrderNo()
    orderInfo.pid = item.id
    // 再获取uid
  }
  const getList = async () => {
    shopInfo.value = await get('/api/program/getAll')
  }

  const isOpen = async () => {
    const aliPayIsOpen = await get('/api/aliPay/isOpen')
    aliPay.cardVisible.value = aliPayIsOpen.status === 1
    const wechatPayIsOpen = await get('/api/wechatPay/isOpen')
    wechatPay.cardVisible.value = wechatPayIsOpen.status === 1
  }

  onMounted(async () => {
    await getList()
    await isOpen()
  })

  const aliPay = {
    codeVisible: ref<boolean>(false),
    cardVisible: ref<boolean>(false),
    url: ref(),
    loading: ref(),
    key: ref(0),
    doPay: () => {
      payTypeVisible.value = false
      aliPay.codeVisible.value = true
      aliPay.loading.value = true
      const { amount, pid, title, orderTradeNo } = orderInfo
      aliPay.url.value = apiUrl(
        `/api/pay/prepay?amount=${amount}&pid=${pid}&title=${title}&outTradeNo=${orderTradeNo}&type=0`
      )
      aliPay.key.value++
      request(orderInfo.orderTradeNo)
    }
  }
  const wechatPay = {
    codeVisible: ref<boolean>(false),
    cardVisible: ref<boolean>(false),
    url: ref(),
    loading: ref(),
    key: ref(0),
    doPay: async () => {
      payTypeVisible.value = false
      wechatPay.codeVisible.value = true
      wechatPay.loading.value = true
      const { amount, pid, title, orderTradeNo } = orderInfo
      wechatPay.url.value = apiUrl(
        `/api/pay/prepay?amount=${amount}&pid=${pid}&title=${title}&outTradeNo=${orderTradeNo}&type=1`
      )
      wechatPay.key.value++
      request(orderInfo.orderTradeNo)
    }
  }

  const isStopPolling = computed(() => {
    return !aliPay.codeVisible.value && !wechatPay.codeVisible.value
  })

  // Payment result polling
  const request = (order: string) => {
    const pollInterval = 2000 // Polling frequency 2s per time
    const pollDuration = 180000 // Polling duration 3min
    const startTime = Date.now()
    const pollingInterval = setInterval(async () => {
      if (Date.now() - startTime > pollDuration) {
        console.log('请求超时')
        MessagePlugin.closeAll()
        await MessagePlugin('warning', '支付超时！')
        clearInterval(pollingInterval)
        closeCodeVisible()
        return
      }
      if (isStopPolling.value) {
        console.log('取消支付')
        clearInterval(pollingInterval)
        return
      }
      const response = await post('/api/order/isPaid', { order })
      if (response.status === 'success') {
        console.log('请求成功')
        closeCodeVisible()
        MessagePlugin.closeAll()
        await MessagePlugin('success', '支付成功，请前往用户中心管理授权！', 5000)
        clearInterval(pollingInterval)
        return
      }
      console.log('请求继续')
    }, pollInterval)
    const closeCodeVisible = () => {
      wechatPay.codeVisible.value = false
      aliPay.codeVisible.value = false
    }
  }

  return {
    shopInfo,
    payTypeVisible,
    aliPay,
    buyAuthorization,
    wechatPay,
    isStopPolling
  }
})
